import { NextRequest, NextResponse } from 'next/server'
import { getUserFromRequest } from '@/lib/auth'
import { downloadVideoFiles, downloadMultipleVideos } from '@/lib/fileDownloader'

export async function POST(request: NextRequest) {
  try {
    const user = await getUserFromRequest(request)
    
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const body = await request.json()
    const { videoId, videoIds } = body

    if (videoId) {
      // 单个视频下载
      const result = await downloadVideoFiles(videoId)
      
      if (result.success) {
        return NextResponse.json({
          success: true,
          message: '文件下载完成'
        })
      } else {
        return NextResponse.json({
          success: false,
          error: result.error
        }, { status: 400 })
      }
    } else if (videoIds && Array.isArray(videoIds)) {
      // 批量下载
      const result = await downloadMultipleVideos(videoIds)
      
      return NextResponse.json({
        success: true,
        message: `下载完成: ${result.success} 成功, ${result.failed} 失败`,
        details: {
          success: result.success,
          failed: result.failed,
          errors: result.errors
        }
      })
    } else {
      return NextResponse.json(
        { error: '请提供 videoId 或 videoIds' },
        { status: 400 }
      )
    }

  } catch (error) {
    console.error('Download error:', error)
    return NextResponse.json(
      { error: '下载失败' },
      { status: 500 }
    )
  }
}
